<template>
  <div id="app">
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="1">首页</el-menu-item>
      <el-menu-item index="2">我的订单</el-menu-item>
      <el-menu-item v-if="user && user.com_member_type === 1" index="3">
        班级订单
      </el-menu-item>
      <el-menu-item v-else index="3" :disabled="true">班级订单</el-menu-item>
      <el-menu-item index="4">我的信息</el-menu-item>
    </el-menu>
    <div class="line"></div>
    <div v-if="activeIndex === '1'" class="book-list">
      <div v-for="book in books" :key="book.id" class="book-container">
        <el-checkbox v-model="book.selected" @change="handleCheckboxChange(book)"></el-checkbox>
        <div class="book-cover">
          <img :src="book.coverImageUrl" alt="封面图片" class="cover-image" />
        </div>
        <div class="book-details">
          <div class="book-info">
            <h3 class="book-title">{{ book.name }}</h3>
            <p class="book-author">作者: {{ book.author }}</p>
            <p class="book-price">价格: {{ book.price }}元</p>
            <p class="book-category">分类: {{ book.category }}</p>
            <p class="book-description">描述: {{ book.description }}</p>
          </div>
          <div class="book-selector">
            <el-input-number v-model="book.quantity" :min="0" :max="9999999" label="数量" @change="handleChange(book)">
            </el-input-number>
          </div>
        </div>
      </div>
    </div>
    <div v-else-if="activeIndex === '2'">
      <UserOrder />
    </div>
    <div v-if="activeIndex === '3' && user && user.com_member_type === 1">
      <ClassOrder />
    </div>
    <UserInfo v-if="activeIndex === '4'" />
    <el-button v-if="activeIndex === '1'" type="text" class="confirm-button" @click="confirmSelection">
      确认
    </el-button>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import UserInfo from "./UserInfo.vue";
import { fetchBooks, fetchCoverImage } from "@/api/api";
import axios from "axios";
import UserOrder from "./UserOrder.vue";
import ClassOrder from "./ClassOrder.vue";

export default {
  name: "UserIndex",
  components: {
    UserInfo,
    UserOrder,
    ClassOrder,
  },
  setup() {
    const activeIndex = ref("1");
    const user = ref(null);
    const books = ref([]);
    

    const handleSelect = (index) => {
      if (index === "3" && (!user.value || user.value.com_member_type !== 1)) {
        return;
      }
      activeIndex.value = index;
    };

    const handleChange = (book) => {
      console.log(`${book.name} 的数量: `, book.quantity);
      if (book.quantity <= 0) {
        book.selected = false;
      }
    };

    const handleCheckboxChange = (book) => {
      console.log(`书籍 ${book.name} 被选中: `, book.selected);
      if (!book.selected) {
        book.quantity = 0;
      }
    };

    const confirmSelection = async () => {
      const selectedBooksData = books.value
        .filter((book) => book.selected)
        .map((book) => ({
          learning_material_id: book.id,
          quantity: book.quantity,
        }));

      const userData = JSON.parse(localStorage.getItem("user"));
      try {
        const checkOrderResponse = await axios.get(
          "/api/v1/order/check_if_student_created",
          {
            headers: {
              "Content-Type": "application/json",
            },
            withCredentials: true,
          }
        );

        if (checkOrderResponse.data.code === 200) {
          const orderId = checkOrderResponse.data.data.id;
          //console.log(orderId);
          await axios.post(
            "/api/v1/order/update",
            {
              id: orderId,
              order_details: selectedBooksData,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
              withCredentials: true,
            }
          );
          console.log("订单更新成功");
          ElMessage({
        message: '订单更新成功',
        type: 'success',
      });
          //console.log(selectedBooksData);
        } else if (checkOrderResponse.data.code === 400) {
          await axios.post(
            "/api/v1/order/create",
            {
              student_id: userData.id,
              order_details: selectedBooksData,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
              withCredentials: true,
            }
          );
          console.log("订单创建成功");
          ElMessage({
        message: '订单创建成功',
        type: 'success',
      });
          //console.log(selectedBooksData);
        } else {
          console.error("检查订单状态失败");
        }
      } catch (error) {
        console.error("订单操作失败:", error);
      }
    };

    onMounted(async () => {
      const userData = localStorage.getItem("user");
      if (userData) {
        user.value = JSON.parse(userData);
        await fetchBooksInfo();
      }
    });

    const fetchBooksInfo = async () => {
  try {
    const response = await fetchBooks();
    console.log("从后端获取的图书信息：", response.data);
    const booksData = response.data.data.map((book) => ({
      ...book,
      quantity: 1,
      selected: true,
    }));

    // 学生的信息中包含的semester_id
    const userSemesterId = user.value.semester_id;
    const filteredBooks = booksData.filter((book) => {
      const isApplicableCollege = user.value.college_id ? book.applicable_college_ids.split(',').includes(user.value.college_id.toString()) : true;
      const isApplicableSemester = userSemesterId ? book.applicable_semester_id === userSemesterId.toString() : true;
      return isApplicableCollege && isApplicableSemester;
    });

    const booksWithCover = await Promise.all(
     filteredBooks.map(async (book) => {
      if (book.cover_image_id) {
        try {
          const coverImage = await fetchCoverImage(book.cover_image_id);
          const coverImageUrl = URL.createObjectURL(coverImage.data);
          return {
            ...book,
            coverImageUrl,
          };
        } catch (error) {
          console.error(`获取书籍 ${book.name} 的封面图片失败:`, error);
          return book;
        }
      } else {
        console.warn(`书籍 ${book.name} 没有封面图片`);
        return book;
      }
    })
  );

  books.value = booksWithCover;
 } catch (error) {
  console.error("获取图书信息失败:", error);
}
};

    return {
      activeIndex,
      handleSelect,
      user,
      books,
      handleChange,
      handleCheckboxChange,
      confirmSelection,
    };
  },
};
</script>

<style>
.book-list {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.book-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.book-cover {
  margin-right: 20px;
}

.cover-image {
  width: 160px;
  height: 160px;
  border-radius: 4px;
  object-fit: cover;
}

.book-details {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
  justify-content: space-between;
  align-items: center;
}

.book-info {
  flex-grow: 1;
}

.book-title {
  font-size: 1.2em;
  font-weight: bold;
}

.book-author,
.book-price,
.book-category,
.book-description {
  margin: 4px 0;
  color: #666;
}

.book-selector {
  margin-left: 20px;
}

.confirm-button {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.confirm-button:hover {
  background-color: #66b1ff;
}
</style>
